<?php

namespace app\data\controller\api;

use app\data\service\CarService;
use think\admin\Controller;
use think\admin\extend\DataExtend;

/**
 * 检测站管理
 * Class MonitoringStation
 * @package app\data\controller\shop
 */
class MonitoringStation extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'CarMonitoringStation';

    /**
     * 获取检测站
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $data = $this->_vali([
            'province.default' => '',
            'city.default' => '',
        ]);

        $query = $this->app->db->name($this->table)->field('id,name')->where('deleted', 0)->where('status', 1);
        if (!empty($data['province'])) {
            $query->where('province', $data['province']);
        }
        if (!empty($data['city'])) {
            $query->where('city', $data['city']);
        }
        $result = $query->order('id desc')->select();
        $this->success('获取检测站数据！', $result);
    }

    /**
     * @api            {get} data/api/public/normal-monitoring-station
     * @apiName        司机获取可用的检测站
     * @apiStatus      working
     * @apiDescription 司机获取可用的检测站-描述
     * @apiPermission  token
     * @apiParam {string} province 省
     * @apiParam {string} city 市
     * @apiParam {string} long 经度
     * @apiParam {string} lat 纬度
     * @apiSuccess {object} data
     * @apiSuccess {string} data.id 检测站ID
     * @apiSuccess {string} data.name 检测站名称
     * @apiSuccess {string} data.distance 距离
     */
    public function userGet()
    {
        $data = $this->_vali([
            'name.default' => '',
            'province.default' => '',
            'city.default' => '',
            'long.require' => '经度不能为空',
            'lat.require' => '纬度不能为空',
        ]);

        $uuids = $this->app->db->name('data_user')->where('service_provider_status', 1)->where('status', 1)->select()->toArray();
        $uuids = array_column($uuids, 'id');

        $ids = $this->app->db->name('car_monitoring_station_relation')->whereIn('uuid', $uuids)->where('status', 1)->select()->toArray();
        $ids = array_column($ids, 'car_monitoring_station_id');
        $query = $this->app->db->name($this->table)->whereIn('id', $ids)->where('deleted', 0)->where('status', 1);
        if (!empty($data['name'])) {
            $query->where('name', 'like', "%{$data['name']}%");
        }
        if (!empty($data['province'])) {
            $query->where('province', $data['province']);
        }
        if (!empty($data['city'])) {
            $query->where('city', $data['city']);
        }
        $lolaList = $query->order('id desc')->select()->toArray();
        $ids = array_column($lolaList, 'id');

        $distanceList = [];
        foreach ($lolaList as $lolaKey => $lolaValue) {
            $distance = getDistance($data['long'] ?? '', $data['lat'] ?? '', $lolaValue['long'], $lolaValue['lat']);
            $lolaList[$lolaKey]['distance'] = $distance;
            $distanceList[$lolaValue['id']] = $distance;
        }

        if (count($lolaList) > 0) {
            array_multisort(array_column($lolaList, 'distance'), SORT_ASC, $lolaList);

            $stationIds = array_column($lolaList, 'id');
            $stationIds = implode(',', $stationIds);
            $orderSql = "FIELD(`id`, $stationIds)";


            $response = $this->app->db->name($this->table)
                ->whereIn('id', $ids)
                ->where('deleted', 0)
                ->where('status', 1)
                ->orderRaw($orderSql)
                ->select()
                ->toArray();

            foreach ($response as $key => $store) {
                $response[$key]['distance'] = $this->formatDistance($distanceList[$store['id']] ?? 0);
                $response[$key]['longitude'] = $store['long'];
                $response[$key]['latitude'] = $store['lat'];
            }
        }

        $this->success('获取检测站数据！', $response ?? []);
    }

    /**
     * 格式化距离
     * @param $distance
     * @return string
     */
    private function formatDistance($distance)
    {
        if ($distance > 1000) {
            return (round($distance) / 1000) . '公里';
        } else {
            return round($distance) . 'M';
        }
    }

}